package com.shujing.service.impl;

import com.shujing.constant.MessageConstant;
import com.shujing.exception.FailedException;
import com.shujing.mapper.CategoryMapper;
import com.shujing.pojo.Category;
import com.shujing.service.CategoryService;
import com.shujing.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author 陈书憬
 * @version 1.0
 * 2024/4/8
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 该接口用于新增文章分类
     *
     * @param category
     * @return
     */
    @Override
    public void category(Category category) {
        String categoryName = category.getCategoryName();

        // 如果不存在该分类名称则...
        String name = categoryMapper.selectCategoryName(categoryName);
        if (name != null) {
            throw new FailedException(MessageConstant.CATEGORY_EXITS);
        }

        // 获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        category.setCategoryName(categoryName);       // 分类名称
        category.setUpdateTime(LocalDateTime.now());  // 更新时间
        category.setCreateTime(LocalDateTime.now());  // 生成时间
        category.setCreateUser(userId);               // 创建人

        categoryMapper.insert(category);
    }

    /**
     * 文章分类列表
     * 该接口用于获取当前已登录用户创建的所有文章分类
     *
     * @return
     */
    @Override
    public List<Category> list() {
        // 获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        // 根据id拿到所有当前用户的文章分类列表
        List<Category> categories = categoryMapper.list(userId);
        return categories;
    }

    /**
     * 该接口用于根据ID获取文章分类详情
     *
     * @param id
     * @return
     */
    @Override
    public Category selectDetail(Number id) {
        // 根据id找数据
        Category category = categoryMapper.selectById(id);
        return category;
    }

    /**
     * 更新文章分类
     *
     * @param category
     */
    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    /**
     * 删除文章分类
     * @param id
     */
    @Override
    public void deleteCategory(Integer id) {
        categoryMapper.delete(id);
    }
}
